package com.sk.bilibili.view.fragment.main;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import com.sk.bilibili.R;
import com.sk.bilibili.databinding.FragmentHomeBinding;
import com.sk.bilibili.model.fragment.main.HomeModel;
import com.sk.bilibili.view.fragment.BaseFragment;

import java.util.Map;

public class HomeFragment extends BaseFragment<FragmentHomeBinding, HomeModel> {

    @Override
    protected void afterSetView() {
        initFragment();
        bindEvent();
    }

    private void switchFragment(Fragment fragment) {
        if(lastFragment==fragment)return;
        FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
        transaction.hide(lastFragment);
        lastFragment=fragment;
        transaction.show(lastFragment).commitAllowingStateLoss();
    }

    private Map<Integer,Fragment> fragmentMap;
    private Fragment lastFragment;

    private void initFragment() {
        fragmentMap=model.loadFragment();
        FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
        for (Fragment fragment:fragmentMap.values()){
            transaction.add(R.id.fl_show,fragment).hide(fragment);
        }
        lastFragment=fragmentMap.get(R.id.home);
        transaction.show(lastFragment).commitAllowingStateLoss();
    }

    private void bindEvent() {
        bind.bnvShow.setOnNavigationItemSelectedListener(item -> {
            switchFragment(fragmentMap.get(item.getItemId()));
            return true;
        });
    }

}